package com.bootcamp.mall.filter;

import com.bootcamp.mall.model.Result;
import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebFilter(value = "/api/mall/*")
public class MallFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        // 从context中获取
        String origin = (String) req.getServletContext().getAttribute("origin");
        List<String> mallAuth = (List<String>) req.getServletContext().getAttribute("mallAuth");
        // 设置权限
        resp.setHeader("Access-Control-Allow-Origin",origin);
        resp.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
        resp.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,Content-Type");
        resp.setHeader("Access-Control-Allow-Credentials","true");
        resp.setContentType("text/html;charset=UTF-8");
        // 只有登录才可以访问订单，才可以修改个人信息
        // 先写死
        // 记录当前method及sessionid
        System.out.println("method:   "+req.getMethod() + "\nsession:  "+req.getSession());
        // OPTIONS 直接跳过
        if ("OPTIONS".equals(req.getMethod())) {
            chain.doFilter(req, resp);
            return;
        }
        // 判断当前是否为 data,updatePwd,updateUserData,getOrderByState,settleAccounts,confirmReceive,pay,addOrder,deleteOrder,askGoodMsg,sendComment
        String op = req.getRequestURI().replace(req.getContextPath() + "/api/mall/", "");
        if (mallAuth.contains(op)){
            // 需要验证登录
            Object userId = req.getSession().getAttribute("userId");
            if (userId==null){
                resp.getWriter().println(new Gson().toJson(Result.error("当前接口仅允许登陆后访问！")));
                return;
            }
        }
        chain.doFilter(req, resp);
    }
}
